package com.waimai.mobile.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.waimai.mobile.R;
import com.waimai.mobile.api.WaiMaiServer;
import com.waimai.mobile.api.entity.Order;
import com.waimai.mobile.api.entity.OrderStatus;
import com.waimai.mobile.api.model.ResponseModel;
import com.waimai.mobile.misc.Util;
import com.waimai.mobile.ui.WaiMaiApp;
import com.waimai.mobile.ui.adapter.OrderFoodItemAdapter;
import com.waimai.mobile.ui.fragment.RestaurantOrderFragment;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import java.text.SimpleDateFormat;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by lin on 2015/6/14.
 */

@EActivity(R.layout.activity_order_detail)
public class OrderDetailActivity extends BaseActivity02{


    public Order order = null;

    @App
    public WaiMaiApp app;

    @RestService
    public WaiMaiServer server;

    @Extra("order")
    public Order orderExtra;

    @Bean
    public OrderFoodItemAdapter adapter;

    @ViewById
    public PtrClassicFrameLayout containerPtr;

    @ViewById
    public ImageView orderStatusIv;

    @ViewById
    public TextView orderStatusTv;

    @ViewById
    public TextView orderMentionMsgTv;

    @ViewById
    public Button orderHandleBtn;

    @ViewById
    public ListView orderFoodLv;

    @ViewById
    public TextView deliveryPriceTv;

    @ViewById
    public TextView totalPriceTv;

    @ViewById
    public TextView orderIdTv;

    @ViewById
    public TextView orderTimeTv;

    @ViewById
    public TextView payModeNameTv;

    @ViewById
    public TextView phoneTv;

    @ViewById
    public TextView addressNameTv;

    @ViewById
    public TextView remarkTv;

    @ViewById
    public LinearLayout commentContainerLL;

    @ViewById
    public RatingBar commentStarLevelRb;

    @ViewById
    public TextView commentContentTv;

    @Override
    public void onOptionMenuCreated() {
        super.onOptionMenuCreated();
        setActionRightIcon(R.mipmap.ic_phone);
        setActionRightVisible(true);
    }


    @AfterViews
    public void afterViews(){
        setActionBarRightClickListener(new ActionBarRightClickListener() {
            @Override
            public void onClick() {
                new AlertDialog.Builder(OrderDetailActivity.this)
                        .setTitle("联系餐厅")
                        .setItems(new String[]{orderExtra.getRestaurant().getPhone()}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        Intent intent = new Intent(Intent.ACTION_CALL);
                                        intent.setData(Uri.parse("tel:" + orderExtra.getRestaurant().getPhone()));
                                        startActivity(intent);
                                        break;
                                }
                            }
                        }).create().show();
            }
        });

        containerPtr.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                getOrder(app.getUser().getUserId(), orderExtra.getOrderId());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        containerPtr.autoRefresh(true);
    }

    public void setOrderStatus(OrderStatus orderStatus){
        switch (orderStatus.getStatusId()){
            case OrderStatus.STATUS_WAIT_CONFIRM:
                orderStatusIv.setImageResource(R.mipmap.ic_dingdantijiao);
                orderStatusTv.setText(orderStatus.getStatusName());
                orderMentionMsgTv.setText("订单已提交，请耐心等待餐厅确认");
                orderHandleBtn.setText("取消订单");
                orderHandleBtn.setVisibility(View.VISIBLE);

                commentContainerLL.setVisibility(View.GONE);
                break;

            case OrderStatus.STATUS_DELIVERY_ING:
                orderStatusIv.setImageResource(R.mipmap.ic_peisongzhong);
                orderStatusTv.setText(orderStatus.getStatusName());
                orderMentionMsgTv.setText("餐厅已接单，美食制作配送中，催单请点击右上方哦");
                orderHandleBtn.setText("确认收货");
                orderHandleBtn.setVisibility(View.VISIBLE);

                commentContainerLL.setVisibility(View.GONE);
                break;

            case OrderStatus.STATUS_NO_COMMENT:
                orderStatusIv.setImageResource(R.mipmap.ic_order_completed);
                orderStatusTv.setText(orderStatus.getStatusName());
                orderMentionMsgTv.setText("订单已完成，祝你用餐开心");
                orderHandleBtn.setText("评价美食");
                orderHandleBtn.setVisibility(View.VISIBLE);

                commentContainerLL.setVisibility(View.GONE);
                break;

            case OrderStatus.STATUS_COMPLITED:
                orderStatusIv.setImageResource(R.mipmap.ic_order_completed);
                orderStatusTv.setText(orderStatus.getStatusName());
                orderMentionMsgTv.setText("感谢您的评价，欢迎再次使用");
                orderHandleBtn.setVisibility(View.GONE);

                commentContainerLL.setVisibility(View.VISIBLE);
                break;

            case OrderStatus.STATUS_CANCELED:
                orderStatusIv.setImageResource(R.mipmap.ic_order_canceled);
                orderStatusTv.setText(orderStatus.getStatusName());
                orderMentionMsgTv.setText("订单已取消，欢迎再次使用");
                orderHandleBtn.setVisibility(View.GONE);

                commentContainerLL.setVisibility(View.GONE);
                break;
        }
    }

    @Click(R.id.orderHandleBtn)
    public void orderHandleBtn(View v){
        if(this.order == null){
            return ;
        }

        switch (order.getOrderstatus().getStatusId()){
            case OrderStatus.STATUS_WAIT_CONFIRM:
                new AlertDialog.Builder(this)
                        .setTitle("取消订单")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                updateOrderStatus(order, OrderStatus.STATUS_CANCELED);
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                break;

            case OrderStatus.STATUS_DELIVERY_ING:
                new AlertDialog.Builder(this)
                        .setTitle("收到美食了吗？")
                        .setPositiveButton("收到了", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                updateOrderStatus(order, OrderStatus.STATUS_NO_COMMENT);
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("没有", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
                break;

            case OrderStatus.STATUS_NO_COMMENT:
                Intent intent = new Intent(this, CommentActivity_.class);
                intent.putExtra("order", order);
                startActivity(intent);
                break;

            case OrderStatus.STATUS_COMPLITED:
                break;

            case OrderStatus.STATUS_CANCELED:
                break;
        }
    }

    @Background
    public void getOrder(Integer userId, Integer orderId){
        try{
            ResponseModel<Order> model = server.order(userId, orderId);
            if(model != null){
                switch (model.getStatus().getStatusCode()){
                    case ResponseModel.STATUS_GET_DATA_SUCCESS:
                        getDataSuccess(model.getData());
                        break;
                    case ResponseModel.STATUS_GET_DATA_NONE:
                        getDataNone();
                        break;
                    case ResponseModel.STATUS_SERVER_ERROR:
                        serverError();
                        break;
                }
            }else{
                serverError();
            }
        }catch (Exception e){
            e.printStackTrace();
            netError();
        }
    }

    @Background
    public void updateOrderStatus(Order order, int statusId){
        try{
            ResponseModel<OrderStatus> model = server.orderUpdate(order.getRestaurant().getRestaurantId(),
                    order.getOrderId(), new OrderStatus(statusId));
            if(model != null){
                switch (model.getStatus().getStatusCode()){
                    case ResponseModel.STATUS_REQUEST_SUCCESS:
                        requestSuccess();
                        break;
                    case ResponseModel.STATUS_REQUEST_FAILED:
                        requestFailed();
                        break;
                    case ResponseModel.STATUS_SERVER_ERROR:
                        serverError();
                        break;
                }
            }else{
                serverError();
            }
        }catch (Exception e){
            e.printStackTrace();
            netError();
        }
    }

    @UiThread
    public void requestSuccess(){
        containerPtr.autoRefresh(true);
        Toast.makeText(this, "操作成功", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void requestFailed(){
        Toast.makeText(this, "操作失败，请重试", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void getDataSuccess(Order order){
        this.order = order;
        containerPtr.refreshComplete();
        initViews(order);
    }

    @UiThread
    public void getDataNone(){
        Toast.makeText(this, "订单不存在，", Toast.LENGTH_LONG).show();
        onBackPressed();
    }

    @UiThread
    public void serverError(){
        containerPtr.refreshComplete();
        Toast.makeText(this, "服务器错误，请重试", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void netError(){
        containerPtr.refreshComplete();
        Toast.makeText(getApplicationContext(), "网络错误，请重试", Toast.LENGTH_SHORT).show();
    }

    public void initViews(Order order){
        setActionBarTitle(order.getRestaurant().getRestaurantName());
        setOrderStatus(order.getOrderstatus());

        adapter.setOrderFoods(order.getOrderfoods());
        orderFoodLv.setClickable(false);
        orderFoodLv.setAdapter(adapter);
        Util.setListViewHeightBasedOnChildren(orderFoodLv);

        deliveryPriceTv.setText(order.getDeliveryPrice() + "");
        totalPriceTv.setText(order.getTotalPrice() + "");
        orderIdTv.setText(order.getOrderId() + "");
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 E HH:mm");
        String orderTimeStr = format.format(order.getOrderTime());
        orderTimeTv.setText(orderTimeStr);
        payModeNameTv.setText(order.getPaymode().getPayModeName());
        phoneTv.setText(order.getReceiveaddress().getPhone());
        addressNameTv.setText(order.getReceiveaddress().getAddressName());
        if(order.getRemark() != null && !"".equals(order.getRemark())){
            remarkTv.setText(order.getRemark());
        }

        if(order.getComment() != null){
            commentStarLevelRb.setRating(order.getComment().getStarLevel());
            if(order.getComment().getContent() != null && !"".equals(order.getComment().getContent())){
                commentContentTv.setText(order.getComment().getContent());
            }
        }
    }
}
